<template>
  <div class="books-list">
    <t-card>
      <t-form ref="form" :data="formData" :label-width="80" colon @reset="onReset" @submit="onSubmit">
        <t-row>
          <t-col :span="10">
            <t-row :gutter="[24, 24]">
              <t-col :span="6">
                <t-form-item label="书名" name="title">
                  <t-input v-model="formData.title" class="form-item-content" type="search" placeholder="请输入书名" />
                </t-form-item>
              </t-col>
              <t-col :span="6">
                <t-form-item label="分类" name="category">
                  <t-input
                    v-model="formData.category"
                    class="form-item-content"
                    type="search"
                    placeholder="请输入分类"
                  />
                </t-form-item>
              </t-col>
            </t-row>
          </t-col>

          <t-col :span="2" class="operation-container">
            <t-button theme="primary" type="submit" :style="{ marginLeft: 'var(--td-comp-margin-s)' }"> 查询 </t-button>
            <t-button type="reset" variant="base" theme="default">重置</t-button>
          </t-col>
        </t-row>
      </t-form>
    </t-card>

    <div class="table-container">
      <div class="header-btns">
        <t-button theme="primary" @click="handleAdd">新增</t-button>
      </div>
      <t-table
        :data="data"
        :columns="COLUMNS"
        :row-key="rowKey"
        :hover="true"
        :pagination="pagination"
        :loading="dataLoading"
        @page-change="onPageChange"
      >
        <template #op="slotProps">
          <t-space>
            <t-link theme="primary" @click="handleEdit(slotProps)">编辑</t-link>
            <t-link theme="danger" @click="handleDelete(slotProps)">删除</t-link>
          </t-space>
        </template>
      </t-table>
    </div>

    <t-dialog
      v-model:visible="dialogVisible"
      :header="dialogTitle"
      :on-close="onDialogClose"
      :on-confirm="onDialogConfirm"
      :footer="true"
      width="900px"
    >
      <t-form ref="dialogForm" :data="dialogData" :rules="rules">
        <t-form-item label="书名" name="title">
          <t-input v-model="dialogData.title" placeholder="请输入书名" />
        </t-form-item>
        <t-form-item label="描述" name="description">
          <t-textarea v-model="dialogData.description" placeholder="请输入描述" />
        </t-form-item>
        <t-form-item label="封面" name="coverImage" required-mark>
          <t-upload
            action="/api/files/uploadFile"
            :size-limit="{ size: 50, unit: 'MB' }"
            accept="image/*"
            @success="onUploadPicSuccess"
            @remove="onUploadPicRemove"
          >
            <t-button v-if="!dialogData.coverImage" class="form-submit-upload-btn" variant="outline"> 上传 </t-button>
            <t-image v-else :src="API_URL + '/api/files/preview/' + dialogData.coverImage" alt="" class="upload-pic" />
          </t-upload>
        </t-form-item>
        <t-form-item label="文件" required-mark name="fileName">
          <t-upload
            action="/api/files/uploadFile"
            :size-limit="{ size: 50, unit: 'MB' }"
            accept=".pdf,.epuc"
            @success="onUploadSuccess"
            @remove="onUploadRemove"
          >
            <t-button class="form-submit-upload-btn" variant="outline"> 上传 </t-button>
          </t-upload>
        </t-form-item>
        <t-form-item label="频道" name="channel" required-mark>
          <t-input v-model="dialogData.channel" placeholder="请输入分类" />
        </t-form-item>
      </t-form>
    </t-dialog>

    <t-dialog
      v-model:visible="deleteVisible"
      header="确认删除"
      body="确定要删除这本书吗？"
      :on-cancel="onDeleteCancel"
      @confirm="onDeleteConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { MessagePlugin, PrimaryTableCol } from 'tdesign-vue-next';
import { onMounted, ref } from 'vue';

import type { EbookEntity } from '@/api/books';
import { addEbook, deleteEbook, getEbookList, updateEbook } from '@/api/books';
import { API_URL } from '@/config/global';

const COLUMNS: PrimaryTableCol[] = [
  { title: '书名', colKey: 'title', width: 200 },
  { title: '描述', colKey: 'description', width: 300, ellipsis: true },
  { title: '分类', colKey: 'category', width: 120 },
  { title: '封面', colKey: 'cover', width: 200, ellipsis: true },
  {
    align: 'left',
    fixed: 'right',
    width: 120,
    colKey: 'op',
    title: '操作',
  },
];
const formData = ref<Partial<EbookEntity>>({});
const data = ref<EbookEntity[]>([]);
const dataLoading = ref(false);
const pagination = ref({
  current: 1,
  pageSize: 10,
  total: 0,
});

const dialogVisible = ref(false);
const dialogTitle = ref('');
const dialogData = ref<Partial<EbookEntity>>({});
const dialogForm = ref();
const deleteVisible = ref(false);
const currentId = ref<number>();

const rules = {
  title: [{ required: true, message: '请输入书名', type: 'error' }],
  channel: [{ required: true, message: '请选择频道', type: 'error' }],
  coverImage: [{ required: true, message: '请上传封面', type: 'error' }],
  fileName: [{ required: true, message: '请上传文件', type: 'error' }],
};

const rowKey = 'id';

async function fetchData() {
  dataLoading.value = true;
  try {
    const res = await getEbookList({
      ...formData.value,
      pagination: {
        current: pagination.value.current,
        size: pagination.value.pageSize,
        total: pagination.value.total,
      },
    });
    const { records, total } = res.data.data;
    console.log('查询书籍成功 --->', res);
    data.value = records;
    pagination.value.total = total;
  } catch (error) {
    MessagePlugin.error('获取数据失败');
  }
  dataLoading.value = false;
}

function onReset() {
  formData.value = {};
  pagination.value.current = 1;
  fetchData();
}

function onSubmit() {
  pagination.value.current = 1;
  fetchData();
}

function onPageChange(curr: any) {
  console.log('curr', curr);
  pagination.value.current = curr.current;
  pagination.value.pageSize = curr.pageSize;
  fetchData();
}

function handleAdd() {
  dialogTitle.value = '新增电子书';
  dialogData.value = {};
  dialogVisible.value = true;
}

function handleEdit({ row }: { row: EbookEntity }) {
  dialogTitle.value = '编辑电子书';
  dialogData.value = { ...row };
  currentId.value = row.id;
  dialogVisible.value = true;
}

function handleDelete({ row }: { row: EbookEntity }) {
  console.log('delete', row);
  currentId.value = row.id;
  deleteVisible.value = true;
}

async function onDialogConfirm() {
  try {
    const validateResult = await dialogForm.value.validate();
    console.log('validateResult', validateResult);
    if (!validateResult) {
      return;
    }
    if (currentId.value) {
      await updateEbook({ ...dialogData.value, id: currentId.value });
      MessagePlugin.success('更新成功');
    } else {
      await addEbook(dialogData.value);
      MessagePlugin.success('添加成功');
    }
    dialogVisible.value = false;
    fetchData();
  } catch (error) {
    MessagePlugin.error('操作失败');
  }
}

function onDialogClose() {
  dialogVisible.value = false;
  dialogData.value = {};
  currentId.value = undefined;
}

function onDeleteCancel() {
  deleteVisible.value = false;
  currentId.value = undefined;
}

async function onDeleteConfirm() {
  if (!currentId.value) return;
  try {
    await deleteEbook(currentId.value);
    MessagePlugin.success('删除成功');
    deleteVisible.value = false;
    currentId.value = undefined;
    fetchData();
  } catch (error) {
    MessagePlugin.error('删除失败');
  }
}

function onUploadSuccess(res: any) {
  dialogData.value.fileName = res.response;
}
function onUploadRemove() {
  dialogData.value.fileName = '';
}

function onUploadPicSuccess(res: any) {
  dialogData.value.coverImage = res.response;
}

function onUploadPicRemove() {
  dialogData.value.coverImage = '';
}

onMounted(() => {
  fetchData();
});
</script>

<style lang="less" scoped>
.books-list {
  padding: 20px;

  .header-btns {
    margin-bottom: 20px;
    margin-top: 20px;
  }

  .operation-container {
    display: flex;
    align-items: flex-end;
    margin-bottom: 8px;
  }
  .upload-pic {
    max-width: 300px;
    max-height: 300px;
  }
}
</style>
